{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "# TravelDreams AI Email Marketing System\n",
    "\n",
    "## Overview\n",
    "This notebook demonstrates an advanced AI agent system for automated travel email marketing using OpenAI's agent framework. The system combines multiple AI agents to create personalized travel destination emails.\n",
    "\n",
    "## Key Features\n",
    "- **🎯 Random Destination Selection**: 8 curated travel destinations with detailed marketing data\n",
    "- **🤖 Multi-Agent Collaboration**: Professional, enthusiastic, and concise email writing agents\n",
    "- **📧 Complete Email Workflow**: Content creation → Subject generation → HTML formatting → Email delivery\n",
    "- **📬 SendGrid Integration**: Automated email delivery with error handling\n",
    "- **🛠️ Function Tools**: Seamless integration using `@function_tool` decorator\n",
    "\n",
    "## Architecture\n",
    "1. **Destination Database**: Rich travel destination data for personalized content\n",
    "2. **Content Agents**: Specialized agents for different writing styles\n",
    "3. **Formatting Agents**: Subject line and HTML conversion specialists  \n",
    "4. **Email Manager**: Orchestrates the complete workflow from creation to delivery\n",
    "5. **Tool Integration**: Automatic conversion of functions and agents into reusable tools\n",
    "\n",
    "Built with OpenAI Agents Framework, SendGrid API, and modern Python patterns.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [],
   "source": [
    "from dotenv import load_dotenv\n",
    "from agents import Agent, Runner, trace, function_tool\n",
    "from openai.types.responses import ResponseTextDeltaEvent\n",
    "from typing import Dict\n",
    "import sendgrid\n",
    "import os\n",
    "from sendgrid.helpers.mail import Mail, Email, To, Content\n",
    "import asyncio\n",
    "import random"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "load_dotenv(override=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Cities and Destinations Database\n",
    "travel_destinations = {\n",
    "    \"Bali, Indonesia\": {\n",
    "        \"highlights\": [\"stunning beaches\", \"ancient temples\", \"lush rice terraces\", \"vibrant cultural scene\"],\n",
    "        \"activities\": [\"surfing\", \"temple hopping\", \"yoga retreats\", \"volcano hiking\"],\n",
    "        \"best_time\": \"April to October\",\n",
    "        \"unique_features\": \"Perfect blend of relaxation and adventure with world-class spas and spiritual experiences\",\n",
    "        \"avg_temp\": \"80°F year-round\"\n",
    "    },\n",
    "    \"Tokyo, Japan\": {\n",
    "        \"highlights\": [\"cutting-edge technology\", \"traditional temples\", \"world-renowned cuisine\", \"cherry blossoms\"],\n",
    "        \"activities\": [\"sushi making classes\", \"traditional tea ceremonies\", \"robot restaurant visits\", \"Mount Fuji day trips\"],\n",
    "        \"best_time\": \"March to May, September to November\",\n",
    "        \"unique_features\": \"Seamless fusion of ultra-modern city life with preserved ancient traditions\",\n",
    "        \"avg_temp\": \"Varies by season, perfect spring and fall weather\"\n",
    "    },\n",
    "    \"Santorini, Greece\": {\n",
    "        \"highlights\": [\"iconic blue-domed churches\", \"dramatic cliff views\", \"world-famous sunsets\", \"volcanic beaches\"],\n",
    "        \"activities\": [\"wine tasting\", \"sunset sailing\", \"archaeological site tours\", \"cooking classes\"],\n",
    "        \"best_time\": \"April to October\",\n",
    "        \"unique_features\": \"Romantic island paradise with unique volcanic landscape and pristine Aegean Sea views\",\n",
    "        \"avg_temp\": \"75°F in peak season\"\n",
    "    },\n",
    "    \"Cape Town, South Africa\": {\n",
    "        \"highlights\": [\"Table Mountain\", \"wine regions\", \"penguin colonies\", \"rich cultural heritage\"],\n",
    "        \"activities\": [\"safari tours\", \"wine tasting\", \"cage diving with great whites\", \"township tours\"],\n",
    "        \"best_time\": \"October to April\",\n",
    "        \"unique_features\": \"Incredible diversity of landscapes, wildlife, and cultures all within driving distance\",\n",
    "        \"avg_temp\": \"70°F in summer\"\n",
    "    },\n",
    "    \"Reykjavik, Iceland\": {\n",
    "        \"highlights\": [\"Northern Lights\", \"geothermal hot springs\", \"dramatic waterfalls\", \"unique Nordic culture\"],\n",
    "        \"activities\": [\"Northern Lights tours\", \"Blue Lagoon relaxation\", \"glacier hiking\", \"whale watching\"],\n",
    "        \"best_time\": \"June to August for mild weather, September to March for Northern Lights\",\n",
    "        \"unique_features\": \"Otherworldly landscapes with geysers, glaciers, and incredible natural phenomena\",\n",
    "        \"avg_temp\": \"50°F in summer, 32°F in winter\"\n",
    "    },\n",
    "    \"Dubai, UAE\": {\n",
    "        \"highlights\": [\"futuristic architecture\", \"luxury shopping\", \"desert safaris\", \"artificial islands\"],\n",
    "        \"activities\": [\"desert camping\", \"luxury shopping\", \"skydiving\", \"yacht charters\"],\n",
    "        \"best_time\": \"November to March\",\n",
    "        \"unique_features\": \"Ultra-modern metropolis rising from the desert with unparalleled luxury experiences\",\n",
    "        \"avg_temp\": \"80°F in winter, 100°F+ in summer\"\n",
    "    },\n",
    "    \"Machu Picchu, Peru\": {\n",
    "        \"highlights\": [\"ancient Incan ruins\", \"breathtaking mountain views\", \"rich indigenous culture\", \"diverse ecosystems\"],\n",
    "        \"activities\": [\"Inca Trail hiking\", \"llama encounters\", \"traditional weaving workshops\", \"Sacred Valley tours\"],\n",
    "        \"best_time\": \"May to September\",\n",
    "        \"unique_features\": \"One of the New Seven Wonders with mystical ancient architecture in stunning mountain setting\",\n",
    "        \"avg_temp\": \"65°F during the day, 45°F at night\"\n",
    "    },\n",
    "    \"Maldives\": {\n",
    "        \"highlights\": [\"overwater bungalows\", \"crystal-clear waters\", \"vibrant coral reefs\", \"private island resorts\"],\n",
    "        \"activities\": [\"snorkeling\", \"diving\", \"spa treatments\", \"sunset fishing\"],\n",
    "        \"best_time\": \"November to April\",\n",
    "        \"unique_features\": \"Ultimate tropical paradise with some of the clearest waters and most luxurious resorts in the world\",\n",
    "        \"avg_temp\": \"84°F year-round\"\n",
    "    }\n",
    "}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Example destination:\n",
      "Destination: Bali, Indonesia\n",
      "Highlights: stunning beaches, ancient temples, lush rice terraces, vibrant cultural scene\n",
      "Unique Features: Perfect blend of relaxation and adventure with world-class spas and spiritual experiences\n"
     ]
    }
   ],
   "source": [
    "# Create a regular function first\n",
    "def _get_random_destination() -> Dict:\n",
    "    \"\"\"Get a random travel destination with detailed information to use in marketing emails\"\"\"\n",
    "    destination_name = random.choice(list(travel_destinations.keys()))\n",
    "    destination_info = travel_destinations[destination_name].copy()\n",
    "    destination_info[\"name\"] = destination_name\n",
    "    return destination_info\n",
    "\n",
    "# Create the function tool version for agents\n",
    "@function_tool\n",
    "def get_random_destination() -> Dict:\n",
    "    \"\"\"Get a random travel destination with detailed information to use in marketing emails\"\"\"\n",
    "    return _get_random_destination()\n",
    "\n",
    "# Test the function using the regular function\n",
    "print(\"Example destination:\")\n",
    "example = _get_random_destination()\n",
    "print(f\"Destination: {example['name']}\")\n",
    "print(f\"Highlights: {', '.join(example['highlights'])}\")\n",
    "print(f\"Unique Features: {example['unique_features']}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Step 1: Agent workflow"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [],
   "source": [
    "instructions1 = \"Professional travel marketer for TravelDreams. \\\n",
    "Write inspiring emails to tourists. Use destination details to create wanderlust.\"\n",
    "\n",
    "instructions2 = \"Enthusiastic travel marketer for TravelDreams. \\\n",
    "Write fun, engaging emails for tourists. Use exciting language about destinations.\"\n",
    "\n",
    "instructions3 = \"Concise travel marketer for TravelDreams. \\\n",
    "Write brief, impactful emails for busy tourists. Focus on compelling destination highlights.\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Enhanced holiday marketing agents with destination tool\n",
    "sales_agent1 = Agent(\n",
    "        name=\"Professional Holiday Marketing Agent\",\n",
    "        instructions=instructions1,\n",
    "        model=\"gpt-4o-mini\",\n",
    "        tools=[get_random_destination]\n",
    ")\n",
    "\n",
    "sales_agent2 = Agent(\n",
    "        name=\"Enthusiastic Holiday Marketing Agent\",\n",
    "        instructions=instructions2,\n",
    "        model=\"gpt-4o-mini\",\n",
    "        tools=[get_random_destination]\n",
    ")\n",
    "\n",
    "sales_agent3 = Agent(\n",
    "        name=\"Concise Holiday Marketing Agent\",\n",
    "        instructions=instructions3,\n",
    "        model=\"gpt-4o-mini\",\n",
    "        tools=[get_random_destination]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "sales_picker = Agent(\n",
    "    name=\"sales_picker\",\n",
    "    instructions=\"You pick the best cold email from the given options. \\\n",
    "Imagine you are a customer and pick the one you are most likely to respond to. \\\n",
    "Do not give an explanation; reply with the selected email only.\",\n",
    "    model=\"gpt-4o-mini\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Travel Marketing Agents\n",
    "\n",
    "Create specialized agents with different writing styles for diverse email marketing approaches:\n",
    "- **Professional Agent**: Inspiring, sophisticated travel content\n",
    "- **Enthusiastic Agent**: Fun, engaging, excitement-driven emails  \n",
    "- **Concise Agent**: Brief, impactful messages for busy travelers\n",
    "\n",
    "Each agent has access to the destination selection tool for personalized content.\n",
    "\n",
    "### Monitor Progress\n",
    "Check the OpenAI trace dashboard: https://platform.openai.com/traces"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Function Tools Integration\n",
    "\n",
    "The `@function_tool` decorator automatically converts Python functions into AI agent tools, eliminating the need for manual JSON schema creation and tool call handling.\n",
    "\n",
    "This replaces the traditional boilerplate of:\n",
    "- Manual JSON schema definitions\n",
    "- Custom `handle_tool_calls()` functions  \n",
    "- Complex if/else logic for tool routing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Enhanced sales agents for tools (with destination functionality)\n",
    "sales_agent1 = Agent(\n",
    "        name=\"Professional Sales Agent\",\n",
    "        instructions=instructions1,\n",
    "        model=\"gpt-4o-mini\",\n",
    "        tools=[get_random_destination]\n",
    ")\n",
    "\n",
    "sales_agent2 = Agent(\n",
    "        name=\"Engaging Sales Agent\",\n",
    "        instructions=instructions2,\n",
    "        model=\"gpt-4o-mini\",\n",
    "        tools=[get_random_destination]\n",
    ")\n",
    "\n",
    "sales_agent3 = Agent(\n",
    "        name=\"Busy Sales Agent\",\n",
    "        instructions=instructions3,\n",
    "        model=\"gpt-4o-mini\",\n",
    "        tools=[get_random_destination]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Agent-to-Tool Conversion\n",
    "\n",
    "Transform any function or agent into a reusable tool with the `@function_tool` decorator.\n",
    "\n",
    "**Key Benefits:**\n",
    "- **Zero Boilerplate**: No manual JSON schema creation required\n",
    "- **Automatic Integration**: Functions become instantly available to agents\n",
    "- **Type Safety**: Automatic parameter validation and type checking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [],
   "source": [
    "@function_tool\n",
    "def send_email(body: str):\n",
    "    \"\"\" Send out an email with the given body to all sales prospects \"\"\"\n",
    "    sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY'))\n",
    "    from_email = Email(\"mantomarchi300@outlook.com\")  # Change to your verified sender\n",
    "    to_email = To(\"mallofrench05@gmail.com\")  # Change to your recipient\n",
    "    content = Content(\"text/plain\", body)\n",
    "    mail = Mail(from_email, to_email, \"Sales email\", content).get()\n",
    "    response = sg.client.mail.send.post(request_body=mail)\n",
    "    return {\"status\": \"success\"}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Automatic Tool Generation\n",
    "\n",
    "The function is now a fully-featured AI tool with automatically generated:\n",
    "- JSON schema for parameters\n",
    "- Type validation\n",
    "- Error handling\n",
    "- Integration with the agent framework"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "FunctionTool(name='send_email', description='Send out an email with the given body to all sales prospects', params_json_schema={'properties': {'body': {'title': 'Body', 'type': 'string'}}, 'required': ['body'], 'title': 'send_email_args', 'type': 'object', 'additionalProperties': False}, on_invoke_tool=<function function_tool.<locals>._create_function_tool.<locals>._on_invoke_tool at 0x1084cdb20>, strict_json_schema=True)"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Let's look at it\n",
    "send_email"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Agents as Tools\n",
    "\n",
    "Agents can be converted into tools using `.as_tool()`, enabling:\n",
    "- **Agent Composition**: Use one agent as a tool for another\n",
    "- **Modular Architecture**: Build complex workflows from simple components\n",
    "- **Reusability**: Share agent capabilities across different contexts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "FunctionTool(name='sales_agent1', description='Write a cold email', params_json_schema={'properties': {'input': {'title': 'Input', 'type': 'string'}}, 'required': ['input'], 'title': 'sales_agent1_args', 'type': 'object', 'additionalProperties': False}, on_invoke_tool=<function function_tool.<locals>._create_function_tool.<locals>._on_invoke_tool at 0x1084cdd00>, strict_json_schema=True)"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tool1 = sales_agent1.as_tool(tool_name=\"sales_agent1\", tool_description=\"Write a cold email\")\n",
    "tool1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Tool Collection Assembly\n",
    "\n",
    "Combine multiple agents and functions into a comprehensive toolkit:\n",
    "\n",
    "**Email Writing Tools:**\n",
    "- 3 specialized marketing agents (Professional, Enthusiastic, Concise)\n",
    "- Email sending function for delivery\n",
    "\n",
    "**Result:** A complete email marketing toolkit ready for orchestration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[FunctionTool(name='marketing_agent1', description='Write an inspiring holiday marketing email for tourists', params_json_schema={'properties': {'input': {'title': 'Input', 'type': 'string'}}, 'required': ['input'], 'title': 'marketing_agent1_args', 'type': 'object', 'additionalProperties': False}, on_invoke_tool=<function function_tool.<locals>._create_function_tool.<locals>._on_invoke_tool at 0x1084cd300>, strict_json_schema=True),\n",
       " FunctionTool(name='marketing_agent2', description='Write an inspiring holiday marketing email for tourists', params_json_schema={'properties': {'input': {'title': 'Input', 'type': 'string'}}, 'required': ['input'], 'title': 'marketing_agent2_args', 'type': 'object', 'additionalProperties': False}, on_invoke_tool=<function function_tool.<locals>._create_function_tool.<locals>._on_invoke_tool at 0x1084cf560>, strict_json_schema=True),\n",
       " FunctionTool(name='marketing_agent3', description='Write an inspiring holiday marketing email for tourists', params_json_schema={'properties': {'input': {'title': 'Input', 'type': 'string'}}, 'required': ['input'], 'title': 'marketing_agent3_args', 'type': 'object', 'additionalProperties': False}, on_invoke_tool=<function function_tool.<locals>._create_function_tool.<locals>._on_invoke_tool at 0x1084cfe20>, strict_json_schema=True),\n",
       " FunctionTool(name='send_email', description='Send out an email with the given body to all sales prospects', params_json_schema={'properties': {'body': {'title': 'Body', 'type': 'string'}}, 'required': ['body'], 'title': 'send_email_args', 'type': 'object', 'additionalProperties': False}, on_invoke_tool=<function function_tool.<locals>._create_function_tool.<locals>._on_invoke_tool at 0x1084cdb20>, strict_json_schema=True)]"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "description = \"Write an inspiring holiday marketing email for tourists\"\n",
    "\n",
    "tool1 = sales_agent1.as_tool(tool_name=\"marketing_agent1\", tool_description=description)\n",
    "tool2 = sales_agent2.as_tool(tool_name=\"marketing_agent2\", tool_description=description)\n",
    "tool3 = sales_agent3.as_tool(tool_name=\"marketing_agent3\", tool_description=description)\n",
    "\n",
    "tools = [tool1, tool2, tool3, send_email]\n",
    "\n",
    "tools"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Complete Email Production System\n",
    "\n",
    "**Multi-Agent Email Workflow:**\n",
    "\n",
    "1. **Content Creation**: Travel writer generates destination-specific content\n",
    "2. **Subject Generation**: Subject writer creates compelling headlines  \n",
    "3. **HTML Formatting**: HTML converter creates beautiful layouts\n",
    "4. **Email Delivery**: SendGrid integration sends formatted emails\n",
    "\n",
    "**Advanced Features:**\n",
    "- Function tool integration with `@function_tool` decorator\n",
    "- Agent-to-tool conversion with `.as_tool()` method\n",
    "- Error handling and status reporting\n",
    "- Comprehensive workflow orchestration\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "subject_instructions = \"Write compelling subjects for holiday emails. \\\n",
    "Create subjects that inspire wanderlust and excite tourists.\"\n",
    "\n",
    "html_instructions = \"Convert travel emails to beautiful HTML. \\\n",
    "Create vacation-inspired layouts that excite tourists.\"\n",
    "\n",
    "subject_writer = Agent(name=\"Holiday Email Subject Writer\", instructions=subject_instructions, model=\"gpt-4o-mini\")\n",
    "subject_tool = subject_writer.as_tool(tool_name=\"subject_writer\", tool_description=\"Write a compelling subject for a holiday marketing email\")\n",
    "\n",
    "html_converter = Agent(name=\"Holiday HTML Email Converter\", instructions=html_instructions, model=\"gpt-4o-mini\")\n",
    "html_tool = html_converter.as_tool(tool_name=\"html_converter\",tool_description=\"Convert a holiday marketing email to beautiful HTML format\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [],
   "source": [
    "@function_tool\n",
    "def send_html_email(subject: str, html_body: str) -> Dict[str, str]:\n",
    "    \"\"\" Send out an email with the given subject and HTML body to all sales prospects \"\"\"\n",
    "    try:\n",
    "        print(f\"📧 Attempting to send email with subject: '{subject}'\")\n",
    "        \n",
    "        # Check if API key exists\n",
    "        api_key = os.environ.get('SENDGRID_API_KEY')\n",
    "        if not api_key:\n",
    "            error_msg = \"SENDGRID_API_KEY not found in environment variables\"\n",
    "            print(error_msg)\n",
    "            return {\"status\": \"error\", \"error\": error_msg}\n",
    "        \n",
    "        print(f\"API key found: {api_key[:10]}...\")\n",
    "        \n",
    "        sg = sendgrid.SendGridAPIClient(api_key=api_key)\n",
    "        from_email = Email(\"mantomarchi300@outlook.com\")  # Change to your verified sender\n",
    "        to_email = To(\"mallofrench05@gmail.com\")  # Change to your recipient\n",
    "        \n",
    "        print(f\"📤 Sending from: {from_email.email} to: {to_email.email}\")\n",
    "        \n",
    "        content = Content(\"text/html\", html_body)\n",
    "        mail = Mail(from_email, to_email, subject, content).get()\n",
    "        \n",
    "        response = sg.client.mail.send.post(request_body=mail)\n",
    "        \n",
    "        print(f\"SendGrid response status: {response.status_code}\")\n",
    "        print(f\"Email sent successfully!\")\n",
    "        \n",
    "        return {\n",
    "            \"status\": \"success\", \n",
    "            \"message\": f\"Email sent! Status: {response.status_code}\",\n",
    "            \"subject\": subject\n",
    "        }\n",
    "        \n",
    "    except Exception as e:\n",
    "        error_msg = f\"Email sending failed: {str(e)}\"\n",
    "        print(error_msg)\n",
    "        return {\"status\": \"error\", \"error\": error_msg}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Simple tools for email formatting and sending\n",
    "tools = [subject_tool, html_tool, send_html_email]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[FunctionTool(name='subject_writer', description='Write a compelling subject for a holiday marketing email', params_json_schema={'properties': {'input': {'title': 'Input', 'type': 'string'}}, 'required': ['input'], 'title': 'subject_writer_args', 'type': 'object', 'additionalProperties': False}, on_invoke_tool=<function function_tool.<locals>._create_function_tool.<locals>._on_invoke_tool at 0x1084ce3e0>, strict_json_schema=True),\n",
       " FunctionTool(name='html_converter', description='Convert a holiday marketing email to beautiful HTML format', params_json_schema={'properties': {'input': {'title': 'Input', 'type': 'string'}}, 'required': ['input'], 'title': 'html_converter_args', 'type': 'object', 'additionalProperties': False}, on_invoke_tool=<function function_tool.<locals>._create_function_tool.<locals>._on_invoke_tool at 0x1084cfb00>, strict_json_schema=True),\n",
       " FunctionTool(name='send_html_email', description='Send out an email with the given subject and HTML body to all sales prospects', params_json_schema={'properties': {'subject': {'title': 'Subject', 'type': 'string'}, 'html_body': {'title': 'Html Body', 'type': 'string'}}, 'required': ['subject', 'html_body'], 'title': 'send_html_email_args', 'type': 'object', 'additionalProperties': False}, on_invoke_tool=<function function_tool.<locals>._create_function_tool.<locals>._on_invoke_tool at 0x1084ce7a0>, strict_json_schema=True)]"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tools"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [],
   "source": [
    "simple_email_instructions = \"\"\"Email formatter for TravelDreams holiday emails.\n",
    "\n",
    "Process:\n",
    "1. Use subject_writer for compelling subject\n",
    "2. Use html_converter for beautiful HTML formatting\n",
    "3. Use send_html_email to send the formatted email\n",
    "\n",
    "Create beautiful holiday emails that inspire travel.\"\"\"\n",
    "\n",
    "emailer_agent = Agent(\n",
    "    name=\"Simple Email Manager\",\n",
    "    instructions=simple_email_instructions,\n",
    "    tools=tools,\n",
    "    model=\"gpt-4o-mini\",\n",
    "    handoff_description=\"Convert an email to beautiful HTML and send it\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✅ Travel writer agent created successfully!\n"
     ]
    }
   ],
   "source": [
    "# Create a travel writer agent \n",
    "travel_writer = Agent(\n",
    "    name=\"Travel Content Writer\",\n",
    "    instructions=\"Professional travel content writer for TravelDreams. Create engaging travel emails using destination details to inspire wanderlust and excitement about travel destinations.\",\n",
    "    model=\"gpt-4o-mini\",\n",
    "    tools=[get_random_destination]\n",
    ")\n",
    "\n",
    "print(\"✅ Travel writer agent created successfully!\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Setup tools and handoffs for the complete system\n",
    "# Use different variable names to avoid conflicts\n",
    "marketing_tools = [tool1, tool2, tool3]\n",
    "handoffs = [emailer_agent]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "📧 Generating email...\n",
      "\n",
      "📧 Attempting to send email with subject: 'Unleash Your Inner Explorer: Santorini Awaits! 🌊✨'\n",
      "API key found: SG.zz80-8u...\n",
      "📤 Sending from: mantomarchi300@outlook.com to: mallofrench05@gmail.com\n",
      "SendGrid response status: 202\n",
      "Email sent successfully!\n",
      "📧 Email sent successfully!\n"
     ]
    }
   ],
   "source": [
    "# Create a super explicit agent with detailed instructions\n",
    "ultimate_email_agent = Agent(\n",
    "    name=\"Ultimate Email Agent\",\n",
    "    instructions=\"\"\"You are an email automation system. Your job is to create and send a complete travel email.\n",
    "\n",
    "MANDATORY STEPS - YOU MUST DO ALL OF THESE:\n",
    "\n",
    "1. FIRST: Call travel_writer tool with input \"Create a travel email with destination details\"\n",
    "2. SECOND: Call subject_writer tool with the email content to create a subject line  \n",
    "3. THIRD: Call html_converter tool with the email content to create HTML version\n",
    "4. FOURTH: Call send_html_email tool with the subject and HTML body to send the email\n",
    "\n",
    "DO NOT STOP until you have completed ALL 4 steps. Each step depends on the previous one.\n",
    "Be persistent and make sure the email gets sent.\"\"\",\n",
    "    tools=[\n",
    "        travel_writer.as_tool(\"travel_writer\", \"Create travel email with destination details\"), \n",
    "        subject_tool, \n",
    "        html_tool, \n",
    "        send_html_email\n",
    "    ],\n",
    "    model=\"gpt-4o-mini\"\n",
    ")\n",
    "\n",
    "print(\"📧 Generating email...\")\n",
    "print()\n",
    "\n",
    "with trace(\"Ultimate Email System\"):\n",
    "    final_result = await Runner.run(\n",
    "        ultimate_email_agent, \n",
    "        \"Create a complete travel marketing email: use travel_writer, then subject_writer, then html_converter, then send_html_email. Complete all 4 steps.\", \n",
    "        max_turns=15\n",
    "    )\n",
    "\n",
    "print(\"📧 Email sent successfully!\")\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Monitoring & Verification\n",
    "- **OpenAI Traces**: https://platform.openai.com/traces\n",
    "- **Email Delivery**: Check your inbox for the formatted travel email\n",
    "- **System Logs**: Review console output for detailed execution steps\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
